import { Node, UITransform, v2, v3, Vec3 } from "cc";
import { app } from "db://app-game/core/app";
import { ecs } from "db://app-game/libs/ecs/ECS";
import FlowGrid from "db://app-game/libs/math/pathfinding/flow-field/FlowGrid";
import { MapE } from "../Map";
import { MapBaseInfo, MapModelComp } from "../model/MapModelComp";
import { MapRenderModelComp } from "../model/MapRenderModelComp";

/** 地图渲染系统 */
@ecs.register("MapRender")
export class MapRenderSystem
  extends ecs.ComblockSystem
  implements ecs.IEntityEnterSystem, ecs.ISystemUpdate
{
  filter(): ecs.IMatcher {
    return ecs.allOf(MapModelComp, MapRenderModelComp);
  }
  entityEnter(map: MapE): void {
    // 1.计算当前人物位置
    // 2.当前角色去向的位
    // 3.获取中心地图索引
    // 4.判断中心地图是否变化
    // 5.获取周围8块地图那几块需要加载
    // 6.删除不需要加载的地图
  }

  update(map: MapE, dt: number): void {
    // 1.获取当前角色所在地图信息
    const mapRenderModel = map.get(MapRenderModelComp);
    if (!mapRenderModel.target) return;

    let centerPos;
    if (mapRenderModel.target instanceof Node) {
      let wPos = mapRenderModel.target
        .getComponent(UITransform)
        .convertToWorldSpaceAR(v3(0, 0, 0));

      let nPos = app.gui.game
        .getComponent(UITransform)
        .convertToNodeSpaceAR(wPos);
      centerPos = nPos;
    } else {
      centerPos = mapRenderModel.target;
    }

    // 1.九宫格渲染
    this.dinâmicaMapRender(map, centerPos);

    // 2.更新目标
    this.updateFlowTarget(map, centerPos);
  }

  /** 九宫格地图渲染 */
  dinâmicaMapRender(map: MapE, centerPos: Vec3): void {
    const mapRenderModel = map.get(MapRenderModelComp);
    const { mapNodesMap, tileWidth, chunkMapWidth, chunkMapHeight } =
      map.get(MapModelComp);

    const { mapInfo } = map.computedMapIndex(centerPos, v3(0, 0));

    if (
      mapInfo.id ===
      `${mapRenderModel.currentMapIndex.row}-${mapRenderModel.currentMapIndex.col}`
    )
      return;
    mapRenderModel.currentMapIndex = {
      row: Number(mapInfo.id.split("-")[0]),
      col: Number(mapInfo.id.split("-")[1]),
    };

    // 2.获取需要渲染的地图信息
    const { mapRenderArray, width, height } = this.getLoadMap(map, mapInfo);

    // 3.设置地图流动网格
    const topLeftPos = v2(
      mapNodesMap.get(mapRenderArray[0]).minX,
      mapNodesMap.get(mapRenderArray[0]).maxY
    );
    mapRenderModel.flowGrid = new FlowGrid(
      tileWidth,
      topLeftPos,
      width,
      height
    );

    // 4.渲染地图
    mapNodesMap.forEach((item) => {
      const index = mapRenderArray.findIndex((v) => item.id === v);
      if (index > -1) {
        const row = Math.floor(index / (height / chunkMapHeight));
        const col = index % (width / chunkMapWidth);
        const offset = {
          row,
          col,
        };
        this.mapRender(item.id, map, offset);
      } else {
        if (item.rendering) {
        }
        item.rendering = false;
      }
    });

    // 5.更新地图逻辑
  }

  /** 获取需要加载的地图 */
  getLoadMap(
    map: MapE,
    mapInfo: MapBaseInfo
  ): { mapRenderArray: string[]; width: number; height: number } {
    const { chunkMapHeight, chunkMapWidth } = map.get(MapModelComp);
    const { mapTable } = map.get(MapModelComp).data;

    const mapIndex = mapInfo.id.split("-");
    let mapRenderArray = [`${mapInfo.id}`];
    let width = 3 * chunkMapWidth;
    let height = 3 * chunkMapHeight;

    // top
    if (mapIndex[0] && mapIndex[0] !== "0") {
      let row = Number(mapIndex[0]) - 1;
      mapRenderArray.push(`${row}-${mapIndex[1]}`);
    } else {
      // 如果没有上面则地图高度减少1000
      height -= chunkMapHeight;
    }

    // bottom
    if (mapIndex[0] && mapIndex[0] !== `${mapTable.length - 1}`) {
      let row = Number(mapIndex[0]) + 1;
      mapRenderArray.push(`${row}-${mapIndex[1]}`);
    } else {
      // 如果没有上面则地图高度减少1000
      height -= chunkMapHeight;
    }

    // left
    if (mapIndex[1] && mapIndex[1] !== "0") {
      let col = Number(mapIndex[1]) - 1;
      mapRenderArray.push(`${mapIndex[0]}-${col}`);
    } else {
      width -= chunkMapWidth;
    }

    // right
    if (mapIndex[1] && mapIndex[1] !== `${mapTable[0].length - 1}`) {
      let col = Number(mapIndex[1]) + 1;
      mapRenderArray.push(`${mapIndex[0]}-${col}`);
    } else {
      width -= chunkMapWidth;
    }

    // top left
    if (
      mapIndex[0] &&
      mapIndex[0] !== "0" &&
      mapIndex[1] &&
      mapIndex[1] !== "0"
    ) {
      let row = Number(mapIndex[0]) - 1;
      let col = Number(mapIndex[1]) - 1;
      mapRenderArray.push(`${row}-${col}`);
    }

    // top right
    if (
      mapIndex[0] &&
      mapIndex[0] !== "0" &&
      mapIndex[1] &&
      mapIndex[1] !== `${mapTable[0].length - 1}`
    ) {
      let row = Number(mapIndex[0]) - 1;
      let col = Number(mapIndex[1]) + 1;
      mapRenderArray.push(`${row}-${col}`);
    }

    // bottom left
    if (
      mapIndex[0] &&
      mapIndex[0] !== `${mapTable.length - 1}` &&
      mapIndex[1] &&
      mapIndex[1] !== "0"
    ) {
      let row = Number(mapIndex[0]) + 1;
      let col = Number(mapIndex[1]) - 1;
      mapRenderArray.push(`${row}-${col}`);
    }

    // bottom right
    if (
      mapIndex[0] &&
      mapIndex[0] !== `${mapTable.length - 1}` &&
      mapIndex[1] &&
      mapIndex[1] !== `${mapTable[0].length - 1}`
    ) {
      let row = Number(mapIndex[0]) + 1;
      let col = Number(mapIndex[1]) + 1;
      mapRenderArray.push(`${row}-${col}`);
    }

    mapRenderArray = mapRenderArray.sort();
    return {
      mapRenderArray,
      width,
      height,
    };
  }

  /** 地图渲染 */
  mapRender(id: string, map: MapE, offset: { row: number; col: number }) {
    // 4.添加静态障碍物渲染
    this.loadObstacles();
  }

  /** 加载障碍物 */
  loadObstacles() {
    // mapRenderModel.flowGrid;
  }
  /** 加载静态障碍物 */
  loadStaticObstacle() {}

  /** 删除不需要的地图 */
  deleteMap(id: string, map: MapE) {}

  /** 删除障碍物 */
  deleteObstacles() {}

  /** 删除静态障碍物 */

  /** 更新流动目标位置 */
  updateFlowTarget(map: MapE, target: Vec3) {
    const mapRenderModel = map.get(MapRenderModelComp);
    if (mapRenderModel.flowGrid) {
      mapRenderModel.flowGrid.setGoal(v2(target.x, target.y));
      mapRenderModel.flowGrid.build();
    }
  }
}
